package com.ls.fw.data.impl.nosql.hbase.client.util;


import java.io.IOException;
import java.math.BigInteger;

import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableExistsException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * <p></p>
 * @author ls 2013-11-4 上午11:48:43
 * @version V1.0   
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify by user: {修改人} 2013-11-4
 * @modify by reason:{方法名}:{原因}
 */
public class HBaseUtil {

	protected static Logger logger = LoggerFactory.getLogger(HBaseUtil.class);

	/**
	 * 获取当前时间为版本号
	 * 
	 * @return
	 */
	public static long getVersion() {
		// java.util.Date.getTime() 或者 System.currentTimeMillis()
		return System.currentTimeMillis();
	}

	/**
	 * 转化为字符串
	 * 
	 * @param b
	 * @return
	 */
	public static String toString(byte[] b) {
		return new String(b);
	}

	/**
	 * 转化为字节数组
	 * null 值返回null
	 * @param str
	 * @return
	 */
	public static byte[] toBytes(String str) {
		if(str==null){
			return null;
		}
		return Bytes.toBytes(str);
	}

	public static boolean createTable(HBaseAdmin admin, HTableDescriptor table,
			byte[][] splits) throws IOException {
		try {
			if (splits == null) {
				admin.createTable(table);
			} else {
				admin.createTable(table, splits);
			}
			return true;
		} catch (TableExistsException e) {
			logger.info("table " + table.getNameAsString() + " already exists");
			return false;
		}
	}

	public static byte[][] getHexSplits(String startKey, String endKey,
			int numRegions) {
		byte[][] splits = new byte[numRegions - 1][];
		BigInteger lowestKey = new BigInteger(startKey, 16);
		BigInteger highestKey = new BigInteger(endKey, 16);
		BigInteger range = highestKey.subtract(lowestKey);
		BigInteger regionIncrement = range.divide(BigInteger
				.valueOf(numRegions));
		lowestKey = lowestKey.add(regionIncrement);
		for (int i = 0; i < numRegions - 1; i++) {
			BigInteger key = lowestKey.add(regionIncrement.multiply(BigInteger
					.valueOf(i)));
			byte[] b = String.format("%016x", key).getBytes();
			splits[i] = b;
		}
		return splits;
	}
}
